﻿using System.Transactions;
using AutoMapper;
using MediatR;
using Provenance.Domain.User;
using Provenance.ErrorCount;
using Provenance.Infra;
using Provenance.Infra.Interfaces.User;
using Provenance.Write.Api.Application.Command.User;

namespace Provenance.Write.Api.Application.CommandHandler.User
{
    public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ApiResult>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateRoleCommandHandler> _logger;
        private readonly ProvenanceDbContext _dbContext;
        public UpdateRoleCommandHandler(IRoleRepository roleRepository, IRolePermissionRepository rolePermissionRepository, IMapper mapper, ILogger<UpdateRoleCommandHandler> logger, ProvenanceDbContext dbContext)
        {
            _roleRepository = roleRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _mapper = mapper;
            _logger = logger;
            _dbContext = dbContext;
        }

        public async Task<ApiResult> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        var role = await _roleRepository.GetAsync(x => x.RoleId == request.RoleId);
                        role = _mapper.Map(request, role);
                        await _roleRepository.UpdateEntity(role);

                        var list = await _rolePermissionRepository.GetAllAsync(x => x.RoleId == request.RoleId);
                        await _rolePermissionRepository.DeleteRangeEntity(list);
                        var rolePermissionList = new List<RolePermission>();
                        string[] PermissionIds = request.PermissionIds.Split(',');
                        int[] IntIds = PermissionIds.Select(x => int.Parse(x)).ToArray();
                        foreach (var id in IntIds)
                        {
                            rolePermissionList.Add(new RolePermission()
                            {
                                RoleId = request.RoleId,
                                PermissionId = id
                            });
                        }
                        await _rolePermissionRepository.InsertRangeEntity(rolePermissionList);
                        tran.Complete();
                        return ApiResult.Success();
                    }
                    finally
                    {
                        tran.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating role: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
